package com.shijiu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shijiu.common.ResultTest;
import com.shijiu.dao.mapper.UserMapper;
import com.shijiu.params.LoginParam;
import com.shijiu.pojo.Shop;
import com.shijiu.pojo.User;
import com.shijiu.service.LoginService;
import com.shijiu.service.ShopService;
import com.shijiu.service.UserService;
import com.shijiu.utils.JWTUtils;
import com.shijiu.utils.UserThreadLocal;
import com.shijiu.common.ErrorCode;
import com.shijiu.vo.LoginUserVo;
import com.shijiu.common.Result;
import com.shijiu.vo.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author xlj
 * @Date Created in  2023/3/18 14:30
 * @DESCRIPTION:
 * @Version V1.0
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private ShopService shopService;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String ID = "1";

    @Override
    public Result login(LoginParam loginParam) {
        String token = "";
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        String phone = loginParam.getPhone();
        String email = loginParam.getEmail();
        if (StrUtil.isNotBlank(email)) {
            log.info("当前获取的邮箱号为:{}",email);
            String emailCode = redisTemplate.opsForValue().get(email);
            if (StringUtils.isEmpty(emailCode)) {
                return Result.fail(500,"邮箱验证码有误");
            }
            if (!emailCode.equals(String.valueOf(loginParam.getCode()))) {
                return Result.fail(500,"邮箱验证码有误");
            }
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getEmail,email);
            User user = userMapper.selectOne(wrapper);
            if (user == null) {
                return Result.fail(500,"该邮箱号未注册！！！，请联系管理员注册");
            }
            if (ID.equals(user.getDisable())) {
                return Result.fail(ErrorCode.ACCOUNT_DISABLE.getCode(), ErrorCode.ACCOUNT_DISABLE.getMessage());
            }
            Shop shop = new Shop();
            //如果是管理员，店铺id是null，初始化店铺id
            shop.setId(null);
            if(!user.getIsAdmin()) {
                //如果是店主，就查出来店主的店铺id，放入shop中
                shop.setId(shopService.selectShopByUserId(user.getId()).getId());
            }
            //把店主的userid和他的店铺id放入token中，如果是管理员，那shopid为null
            token = JWTUtils.createToken(user.getId(),shop.getId());
        }
        if (StrUtil.isNotBlank(phone)){
            log.info("当前获取的手机号为:{}",phone);
            redisTemplate.opsForValue().set("17677777777","666666");
            //从redis中获取手机验证码
            String userPhoneKey = redisTemplate.opsForValue().get(phone);
            System.out.println(userPhoneKey);
            if (StrUtil.isBlank(userPhoneKey)) {
                return Result.fail(500,"手机验证码有误");
            }
            if (!userPhoneKey.equals(String.valueOf(loginParam.getCode()))) {
                return Result.fail(500,"手机验证码有误");
            }
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userMapper.selectOne(wrapper);
            if (user == null) {
                return Result.fail(500,"该手机号未注册！！！，请联系管理员注册");
            }
            if (ID.equals(user.getDisable())) {
                return Result.fail(ErrorCode.ACCOUNT_DISABLE.getCode(), ErrorCode.ACCOUNT_DISABLE.getMessage());
            }
            Shop shop = new Shop();
            //如果是管理员，店铺id是null，初始化店铺id
            shop.setId(null);
            if(!user.getIsAdmin()) {
                //如果是店主，就查出来店主的店铺id，放入shop中
                shop.setId(shopService.selectShopByUserId(user.getId()).getId());
            }
            //把店主的userid和他的店铺id放入token中，如果是管理员，那shopid为null
            token = JWTUtils.createToken(user.getId(),shop.getId());
        }
        if (StrUtil.isNotBlank(username) || StrUtil.isNotBlank(password)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername,username).select(User::getDisable);
            User users = userMapper.selectOne(queryWrapper);
            if (ID.equals(users.getDisable())) {
                return Result.fail(ErrorCode.ACCOUNT_DISABLE.getCode(), ErrorCode.ACCOUNT_DISABLE.getMessage());
            }
            User user = userService.loginFindUser(username,password);
            if (user == null){
                return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMessage());
            }
            Shop shop = new Shop();
            //如果是管理员，店铺id是null，初始化店铺id
            shop.setId(null);
            if(!user.getIsAdmin()) {
                //如果是店主，就查出来店主的店铺id，放入shop中
                shop.setId(shopService.selectShopByUserId(user.getId()).getId());
            }
            //把店主的userid和他的店铺id放入token中，如果是管理员，那shopid为null
            token = JWTUtils.createToken(user.getId(),shop.getId());

        }
        return Result.success(new Token(token));
    }

    @Override
    public Result loginUserInfo(String token) {
        Map map = UserThreadLocal.get();
        User user = userMapper.selectById((Serializable) map.get("userId"));
        if (user == null) {
            return Result.fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMessage());
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        BeanUtils.copyProperties(user,loginUserVo);
        loginUserVo.setUserId((Integer) map.get("userId"));
        loginUserVo.setShopId((Integer) map.get("shopId"));
        System.out.println("loginUserVo-loginUserInfo-loginServiceImpl"+loginUserVo);
        return Result.success(loginUserVo);
    }

    @Override
    public User checkToken(String token) {
        return null;
    }

    @Override
    public Result logout(String token, HttpServletRequest httpServletRequest) {

        return Result.success(null);
    }

    @Override
    public Result register(LoginParam loginParam) {
        return null;
    }
}
